﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml;
using System.Collections.ObjectModel;
using MoteurAudio;
using System.Xml.Serialization;
using Modele;

namespace Guitar
{
    /// <summary>
    /// Logique d'interaction pour fnt_option.xaml
    /// </summary>
    public partial class OptionsWindow : Window
    {

        

        

        public OptionsWindow()
        {
            InitializeComponent();
            initialiserSons();

        }

  

     
        /* Méthode de gestion du Son */

        public void initialiserSons()
        {

            // on active que la  combo du moteur audio qui va déterminer le reste
            Combo_moteurAudio.IsEnabled = true;
            Combo_peripheriqueLecture.IsEnabled = false;
            Combo_PeripheriqueEnregistrement.IsEnabled = false;


            //Chargements des drivers et interfaces audio
            chargerDrivers();


        }




        public void chargerDrivers()
        {

            Combo_moteurAudio.Items.Add("DirectSound");
            Combo_moteurAudio.Items.Add("Windows Multimedia WaveOut (WMW)");
            Combo_moteurAudio.Items.Add("ASIO");
            // Combo_moteurAudio.Items.Add("Autodétection");

            try
            {
                /* Optient les pilotes de lectures   */
               SystemeAudio.resultat =SystemeAudio.systemAudio.getNumDrivers(ref SystemeAudio.numdrivers);
               SystemeAudio.erreurInfos(SystemeAudio.resultat);

                for (int count = 0; count <SystemeAudio.numdrivers; count++)
                {
                   SystemeAudio.resultat =SystemeAudio.systemAudio.getDriverInfo(count,SystemeAudio.drivername,SystemeAudio.drivername.Capacity, ref SystemeAudio.guid);
                   SystemeAudio.erreurInfos(SystemeAudio.resultat);

                    Combo_peripheriqueLecture.Items.Add(SystemeAudio.drivername.ToString());
                }

                /* Optient les pilotes d'enregistrement */
               SystemeAudio.resultat =SystemeAudio.systemAudio.getRecordNumDrivers(ref SystemeAudio.numdrivers);
               SystemeAudio.erreurInfos(SystemeAudio.resultat);

                for (int count = 0; count <SystemeAudio.numdrivers; count++)
                {
                   SystemeAudio.resultat =SystemeAudio.systemAudio.getRecordDriverInfo(count,SystemeAudio.drivername,SystemeAudio.drivername.Capacity, ref SystemeAudio.guid);
                   SystemeAudio.erreurInfos(SystemeAudio.resultat);

                    Combo_PeripheriqueEnregistrement.Items.Add(SystemeAudio.drivername.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("[Exception] Dans OptionWindows.cs (chargerDrivers())" + ex.Message);
                
            }
        }



        /* Gestion des combox et de leur effet sur le moteur de l'application */

        private void Combo_moteurAudio_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //On stop les modules en cours 
            if (((MainWindow)App.Current.MainWindow).Menu.Module_Accordeur.isActivated)
            {
                ((MainWindow)App.Current.MainWindow).Menu.Module_Accordeur.Start();
            }

            //on réinitialise le système audio
           
            App.audio.Dispose();
            App.audio = null;
            App.audio = new SystemeAudio();

            switch (Combo_moteurAudio.SelectedIndex)
            {
                case 0:
                   SystemeAudio.resultat =SystemeAudio.systemAudio.setOutput(FMOD.OUTPUTTYPE.DSOUND);
                    break;
                case 1:
                   SystemeAudio.resultat =SystemeAudio.systemAudio.setOutput(FMOD.OUTPUTTYPE.WINMM);
                    break;
                case 2:
                   SystemeAudio.resultat =SystemeAudio.systemAudio.setOutput(FMOD.OUTPUTTYPE.ASIO);
                    break;
                /*case 3:
                    resultat = systemAudio.setOutput(FMOD.OUTPUTTYPE.AUTODETECT);
                    break;*/

            }
           SystemeAudio.erreurInfos(SystemeAudio.resultat);

            Combo_peripheriqueLecture.IsEnabled = true;
            Combo_PeripheriqueEnregistrement.IsEnabled = true;
        }


        private void comboBox_peripheriqueLecture_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            int selected = Combo_peripheriqueLecture.SelectedIndex;


           SystemeAudio.resultat =SystemeAudio.systemAudio.setDriver(selected);

            if (SystemeAudio.resultat != FMOD.RESULT.OK)
            {

                MessageBox.Show("Erreur le périphérique selectionné ne supporte pas le moteur de rendu choisi");
                Combo_peripheriqueLecture.SelectedIndex = 0;
            }


        }


        private void Combo_PeripheriqueEnregistrement_SelectedIndexChanged(object sender, SelectionChangedEventArgs e)
        {

            //FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO();
            FMOD.DSP_RESAMPLER resampler = FMOD.DSP_RESAMPLER.MAX;
           SystemeAudio.selectedInterface = Combo_PeripheriqueEnregistrement.SelectedIndex;
            int temp = 0;
            FMOD.SOUND_FORMAT format = FMOD.SOUND_FORMAT.NONE;

           SystemeAudio.resultat =SystemeAudio.systemAudio.setSoftwareFormat(SystemeAudio.OUTPUTRATE, FMOD.SOUND_FORMAT.PCM16, 100, 100, 0);
           SystemeAudio.erreurInfos(SystemeAudio.resultat);

           SystemeAudio.resultat =SystemeAudio.systemAudio.init(32, FMOD.INITFLAGS.NORMAL, (IntPtr)null);
           SystemeAudio.erreurInfos(SystemeAudio.resultat);

           SystemeAudio.resultat =SystemeAudio.systemAudio.getSoftwareFormat(ref SystemeAudio.outputfreq, ref format, ref temp, ref temp, ref resampler, ref temp);
           SystemeAudio.erreurInfos(SystemeAudio.resultat);

        }


        private void EVENT_Sauvegarder_Options_Click(object sender, RoutedEventArgs e)
        {
            SauvegardeXml();
            AppliquerOption();
        
            this.Close(); // on ferme la fenêtre
        }

        // Sauvegarde les options dans un fichier XML
        private void SauvegardeXml()
        {

            XmlSerializer x = new XmlSerializer(App.option.GetType());
            x.Serialize(new StreamWriter("./option.xml"), App.option);
              
          

        }


        private void AppliquerOption()
        {
            if (Lang_en.IsSelected)
            {
                SetTranslation("Langage\\en.xaml");

            }
            else
            {
                SetTranslation("Langage\\fr.xaml");
            }


            if (Lang_note_en.IsSelected)
            {
                App.option.LangueNotationMusicale = Note.Langue.En;

            }
            else
            {
                App.option.LangueNotationMusicale = Note.Langue.Fr;
            }

            UpdateModule(); // On maj les modules
        }



        private void SetTranslation(string _Lang)
        {
            Collection<ResourceDictionary> mergedDicts = Application.Current.Resources.MergedDictionaries;
            if (_Lang == null) return;
            Application.Current.Resources.MergedDictionaries.RemoveAt(0);
            Uri uri = new Uri(_Lang, UriKind.Relative);
            ResourceDictionary dic = Application.LoadComponent(uri) as ResourceDictionary;
            Application.Current.Resources.MergedDictionaries.Insert(0, dic);
        }

        private void OptionsWindows_Closed(object sender, EventArgs e){

           ((MainWindow)App.Current.MainWindow).Menu.MainRibbon.IsEnabled = true;

        }

        private void zoomSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (labelZoomValue != null)
            {
                int val = Convert.ToInt32(zoomSlider.Value * 100);

                labelZoomValue.Content = "" + val.ToString() + "%";
            }
        }

       

        private void zoomSlider_Loaded(object sender, RoutedEventArgs e)
        {
            if (labelZoomValue != null)
            {
                int val = Convert.ToInt32(zoomSlider.Value * 100);

                labelZoomValue.Content = "" + val.ToString() + "%";
            }
        }

        private void UpdateModule()
        {
             App.Pages[App.ModeleurEnCours].Remplir(App.PartitionEnCours, App.PisteEnCours);
        }        


}

}
